package com.hx.mypetstore.ui.cart;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hx.mypetstore.Bean.Cart;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CartFragment extends Fragment implements View.OnClickListener, ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface{

    private static final String TAG = "CartFragment";

    /**
     * 全选框
     */
    private CheckBox ckAll;

    /**
     * 总额
     */
    private TextView tvShowPrice;

    /**
     * 结算
     */
    private TextView tvSettlement;

    /**
     * 编辑按钮
     */
    private TextView btnEdit;

    /**
     * 商品列表
     */
    private ListView commodityListView;

    /**
     * context
     */
    private Context mContext;

    /**
     * uId
     */
    private String  userid;



    /**
     * adapter
     */
    private ShoppingCartAdapter shoppingCartAdapter;
    private boolean flag = false;
    private List<Cart> cartList;
    private Integer totalPrice = 0;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_cart,container,false);
        mContext = getContext();
        //初始化数据
        initData();
        cartList = SPUtil.getDataList(mContext, SPConstants.CART_LIST, Cart.class);
        // 初始化View
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //初始化数据
        initData();
        // 初始化View
        initView(getView());
    }

    @Override
    public void onStart() {
        super.onStart();
        //初始化数据
        initData();
        // 初始化View
        initView(getView());
    }

    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //定义一个弹出层dialog
            AlertDialog alert = new AlertDialog.Builder(mContext).create();

            switch (msg.what) {
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求处理失败！获取商品数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //网络请求购物车信息数据成功
                    shoppingCartAdapter = new ShoppingCartAdapter(mContext);
                    shoppingCartAdapter.setCheckInterface(CartFragment.this);
                    shoppingCartAdapter.setModifyCountInterface(CartFragment.this);
                    commodityListView.setAdapter(shoppingCartAdapter);
                    cartList = SPUtil.getDataList(mContext, SPConstants.CART_LIST, Cart.class);
                    shoppingCartAdapter.setShoppingCartBeanList(cartList);
                    break;
                case 2:
                    //购买结算
                    alert.setTitle("提示");
                    alert.setMessage(msg.obj == null ? "购买请求处理失败！"
                            : msg.obj.toString());
                    alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //finish掉购物车窗口
                                    getActivity().finish();
                                }
                            });
                    alert.show();
                    break;
                case 3:
                    //删除商品
                    alert.setTitle("提示");
                    alert.setMessage(msg.obj == null ? "从购物车中移除商品失败！"
                            : msg.obj.toString());
                    alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    alert.show();
                    break;
                case 4:
                    Toast.makeText(mContext, msg.obj == null ? "刷新购物车数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    /**
     * 绑定组件
     * @param view
     */
    private void initView(View view) {
        ckAll = view.findViewById(R.id.ck_all);
        tvShowPrice = view.findViewById(R.id.tv_show_price);
        tvSettlement = view.findViewById(R.id.tv_settlement);
        btnEdit = view.findViewById(R.id.btn_edit);
        commodityListView = view.findViewById(R.id.list_shopping_cart);

        btnEdit.setText("编辑");
        btnEdit.setOnClickListener(this);
        ckAll.setOnClickListener(this);
        tvSettlement.setOnClickListener(this);
    }

    private void initData() {
        String url = HttpURL.GETCART;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "地址数据"+jsonObject.toString());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        message.what = 1;
                        String cart = jsonObject.getString("data");
                        //Json 解析对象
                        JsonParser jsonParser = new JsonParser();
                        JsonArray jsonArray = jsonParser.parse(cart).getAsJsonArray();
                        //JsonArray jsonArray = jsonObject1.getAsJsonArray("msg");
                        Gson gson = new Gson();
                        ArrayList<Cart> list = new ArrayList<>();
                        for (JsonElement add : jsonArray) {
                            Cart addressBean = gson.fromJson(add, Cart.class);
                            list.add(addressBean);
                        }
                        Log.e(TAG, "list"+list);
                        SPUtil.saveDataList(mContext,SPConstants.CART_LIST,list);
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //全选按钮
            case R.id.ck_all:
                if (cartList.size() != 0) {
                    if (ckAll.isChecked()) {
                        for (int i = 0; i < cartList.size(); i++) {
                            cartList.get(i).setIschoice(true);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < cartList.size(); i++) {
                            cartList.get(i).setIschoice(false);
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            case R.id.btn_edit:
                flag = !flag;
                if (flag) {
                    //编辑状态
                    btnEdit.setText("完成");
                    shoppingCartAdapter.isShow(false);
                } else {
                    //编辑完成状态
                    btnEdit.setText("编辑");
                    shoppingCartAdapter.isShow(true);
                    //刷新购物车数据
                    refreshCart();
                }
                break;
            case R.id.tv_settlement: //结算
                //pay();
                break;
        }
    }

    /**
     * 单选框选择操作
     * @param position  元素位置
     * @param isChecked 元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        cartList.get(position).setIschoice(isChecked);
        if (isAllCheck()) {
            ckAll.setChecked(true);
        } else {
            ckAll.setChecked(false);
        }
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 遍历list集合
     *
     * @return
     */
    private boolean isAllCheck() {

        for (Cart group : cartList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }

    /**
     * 增加操作
     * @param position      元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        Cart model = cartList.get(position);
        int currentCount = model.getNum();
        currentCount++;
        model.setNum(currentCount);
        ((TextView) showCountView).setText("商品数量： X" +currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 减少操作
     * @param position      元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        Cart model = cartList.get(position);
        int currentCount = model.getNum();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        model.setNum(currentCount);
        ((TextView) showCountView).setText("商品数量： X" +currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 在编辑完成后，刷新购物车
     */
    private void refreshCart() {
        String cIds = "";
        String numbers = "";

        //选中的需要提交的商品清单
        for (Cart bean : cartList) {
            //拼接商品id
            cIds += bean.getGoodid() + ",";
            //拼接商品数量
            numbers += bean.getNum()+ ",";
        }

        //清理末尾逗号
        cIds = cIds.substring(0, cIds.lastIndexOf(","));
        numbers = numbers.substring(0, numbers.lastIndexOf(","));
        //Log.e(TAG, "商品id "+cIds +"  商品数量："+numbers);

        String url = HttpURL.UPDATECART;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .add("goodid",cIds)
                .add("num",numbers)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "商品数据"+jsonObject.toString());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        message.what = 1;
                        String cart = jsonObject.getString("data");
                        //Json 解析对象
                        JsonParser jsonParser = new JsonParser();
                        JsonArray jsonArray = jsonParser.parse(cart).getAsJsonArray();
                        //JsonArray jsonArray = jsonObject1.getAsJsonArray("msg");
                        Gson gson = new Gson();
                        ArrayList<Cart> list = new ArrayList<>();
                        for (JsonElement add : jsonArray) {
                            Cart addressBean = gson.fromJson(add, Cart.class);
                            list.add(addressBean);
                        }
                        Log.e(TAG, "list"+list);
                        SPUtil.saveDataList(mContext,SPConstants.CART_LIST,list);
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * 删除
     *
     * @param position
     */
    @Override
    public void childDelete(int position) {

        String url = HttpURL.DELETEONE;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();

        //请求体
        Cart cart = cartList.get(position);
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .add("goodid",cart.getGoodid().toString())
                .add("num",cart.getNum().toString())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "商品数据"+jsonObject.toString());
                    Message message = Message.obtain();
                    if (jsonObject.getBoolean("success")) {
                        message.what = 3;
                        message.obj = jsonObject.getString("message");
                    } else {
                        message.what = 0;
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //listView中remove掉item
        cartList.remove(position);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0;
        for (int i = 0; i < cartList.size(); i++) {
            Cart model = cartList.get(i);
            if (model.isChoosed()) {
                totalCount++;
                totalPrice += model.getPrice() * model.getNum();
            }
        }

        //保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");
        String str = df.format(totalPrice);
        tvShowPrice.setText("合计:" + str);
        tvSettlement.setText("结算(" + totalCount + ")");
    }
}